/**
 * Model 数据源
 * 用于 单条记录的增删查改
 */

import axios from 'axios'

export default class ListDataSource {

  constructor (url) {
    this.url = url
    this.debug = true
    this.items = []
    this.meta = {
      currentPage: 1,
      from: 1,
      lastPage: 1,
      path: 'http://example.com/pagination',
      perPage: 15,
      to: 10,
      total: 10
    }
    this.links = {
      first: 'http://example.com/pagination?page=1',
      last: 'http://example.com/pagination?page=1',
      prev: null,
      next: null
    }
  }

  fetchData (params) {
    let self = this;
    let url = self.url;
    return axios.get(url, {params: params}).then(function (response) {
      self.items = [];
      _.forEach(response.data.data, function (value, key) {
        self.items.push(value);
      });
      if (response.data.meta){
        self.meta = response.data.meta;
        if (response.data.meta.pagination){
          self.total = Number.parseInt(response.data.meta.pagination.total);
          self.currentPage = Number.parseInt(response.data.meta.pagination.current_page);
          self.pageCount = Number.parseInt(response.data.meta.pagination.total_pages);
        }else{
          self.total = Number.parseInt(response.data.meta.total);
          self.currentPage = Number.parseInt(response.data.meta.current_page);
          self.pageCount = Number.parseInt(response.data.meta.last_page);
        }
      }else{
        self.total = Number.parseInt(response.data.total);
        self.currentPage = Number.parseInt(response.data.current_page);
        self.pageCount = Number.parseInt(response.data.last_page);
      }

      // typeof successCallback === 'function' && successCallback();
    })
    //   .catch(function (error) {
    //   // Something happened in setting up the request that triggered an Error
    //   self.debug && console.log('Error', error.message);
    //   typeof failedCallback === 'function' && failedCallback();
    // });
  }
}
